import React, { useContext, Dispatch } from 'react';

import { JsonPathRuleGroup, JsonPathRule, JsonPathGroup, Action, Config } from '../../types';
import styles from '../../styles.less';
import { QueryContext } from '../../store';
import RuleGroupConditions from '../rulegroup/RuleGroupConditions';
import RuleGroupActions from '../rulegroup/RuleGroupActions';
import Rule from './Rule';

const RuleGroup: React.FC<{
  config: Config,
  group: JsonPathRuleGroup
}> = (props) => {
  const { group, config } = props;
  const { dispatch } = useContext<{state: JsonPathGroup, dispatch: Dispatch<Action>}>(QueryContext);

  const renderActions = () => {
    return (
      <RuleGroupActions
        config={config}
        path={group.path || ""}
        onClick={(action) => dispatch(action)}
      />
    );
  }

  const renderCondition = () => {
    return (
      <RuleGroupConditions
        config={config}
        not={group.not}
        condition={group.condition}
        path={group.path || ""}
        onChange={(action) => dispatch(action)}
      />
    );
  }

  const renderHeader = () => {
    return (
      <div className={styles.rulegroupheader}>
        {renderCondition()}
        {renderActions()}
      </div>
    );
  }

  const renderItem = () => {
    return group.rules?.map(rule => {
      if ((rule as JsonPathRuleGroup).condition) {
        return (
          <RuleGroup
            key={(rule as JsonPathRuleGroup).path||""}
            config={config}
            group={rule as JsonPathRuleGroup}
          />
        );
      } else {
        return (
          <Rule
            key={(rule as JsonPathRule).path||""}
            path={(rule as JsonPathRule).path||""}
            rule={rule as JsonPathRule}
            config={config}
          />
        );
      }
    });
  }

  return (
    <div className={styles.rulegroup}>
      {renderHeader()}
      {renderItem()}
    </div>
  );
}

export default RuleGroup;
